<?php
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------

namespace app\model;

use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

class User extends Model
{
	protected $name               = 'user';
	protected $autoWriteTimestamp = true;
	protected $insert             = [];
	protected $update             = [];

	const DOUYIN   = 'DouYin';
	const WECHAT   = 'Wechat';
	const PROVIDER = [
		self::DOUYIN => '抖音',
		self::WECHAT => '微信',
	];

	const LEVEL_V1 = 1; // 等级：v1
	const LEVEL_V2 = 2; // 等级：v2
	const LEVEL_V3 = 3; // 等级：v3

	const STATUS_NO  = 0; // 用户已注销
	const STATUS_YES = 1; // 有效用户

	const BIND_STATUS_NO  = 0; // 是否绑定机构 否
	const BIND_STATUS_YES = 1; // 是否绑定机构 是

	public function getCreateTimeAttr($value)
	{
		return $value ? date('Y-m-d H:i:s', $value) : '';
	}

	public function oauth()
	{
		return $this->hasOne('userOauth', 'user_id')
			->bind([
				'provider' => 'provider',
				'platform' => 'platform',
				'openid'   => 'openid',
			]);
	}

	/**
	 * 创建排位树
	 *
	 * @param $pUser
	 * @param $userInfo
	 * @return mixed
	 * @throws DataNotFoundException
	 * @throws DbException
	 * @throws ModelNotFoundException
	 */
	public function createRank($pUserId, $userInfo)
	{
		$rank_prev = [
			'rank'       => '|' . $userInfo['id'] . '|',
			'rank_level' => 0,
			'id'         => 0,
		];
		$pUser     = User::where('id', $pUserId)->where('status', 1)->find();
		if ($pUser) {
			if ($pUser['rank_next_count'] < rankNextMax()) {
				$rank_prev = $pUser;
			} else {
				$rank = '|' . $pUser['id'] . '|';

				$rank_prev = $this->where([
					['rank', 'like', '%' . $rank . '%'],
					['rank_next_count', '<', rankNextMax()],
				])->order(['rank_level', 'rank_next_count', 'id'])->find();
			}
		}

		$update = [
			'rank'       => $rank_prev['rank'] . $userInfo['id'] . '|',
			'rank_level' => $rank_prev['rank_level'] + 1,
			'rank_pid'   => $rank_prev['id'],
		];

		return $this->transaction(function () use ($rank_prev, $userInfo, $update) {

			$rank_prev->save(['rank_next_count' => $rank_prev['rank_next_count'] + 1]);

			$userInfo->save($update);

			return true;
		});
	}

	public function setIncMoney($id, $money)
	{
		return Db::name('user')->where('id', $id)->setInc('money', $money);
	}

	public function setIncTotal($id, $money)
	{
		return Db::name('user')->where('id', $id)->setInc('total', $money);
	}
}
